﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using NOSDC.Entities;
using NOSDC.Pocos;

namespace NOSDC.Repositories 
{
    public sealed class PollRepository : IPollRepository
    {
        private readonly NOSDCContext _db;

        public PollRepository()
        {
            _db = new NOSDCContext();
        }

        public Polls GetLatestPoll()
        {
            return _db.Polls.Where(p => p.CreatedOn < DateTime.Now).OrderByDescending(p => p.CreatedOn).FirstOrDefault();
        }

        public void SubmitAnswer(PollResults result)
        {
            _db.PollResults.AddObject(result);
            _db.SaveChanges();
        }

        public IList<Polls> GetAllPolls()
        {
            return _db.Polls.ToList();
        }

        public void CreatePoll(Polls poll)
        {
            _db.Polls.AddObject(poll);
            _db.SaveChanges();
        }

        public void UpdatePoll(Polls poll)
        {
            _db.Polls.Attach(poll);
            var pollEntry = _db.ObjectStateManager.GetObjectStateEntry(poll);
            pollEntry.SetModified();
            _db.ObjectStateManager.ChangeObjectState(poll, System.Data.EntityState.Modified);
            _db.SaveChanges(SaveOptions.DetectChangesBeforeSave);
        }

        public void DeletePoll(Polls poll)
        {
            _db.DeleteObject(poll);
            _db.SaveChanges();
        }

        /// <summary>
        /// Checks to see if the user has already submitted a response to the poll in question.
        /// </summary>
        /// <param name="userid">user submitting answer</param>
        /// <param name="pollid">the poll the answer belongs too</param>
        /// <returns></returns>
        public bool GetPollResult(Guid userid, int pollid)
        {
            return _db.PollResults.Where(pr => pr.PollID.Equals(pollid)).Any(pr => pr.SubmittedBy.Equals(userid));
        }
    }
}
